home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / gr564s.zip / SRC / RCSEDIT.C < prev    next >
C/C++ Source or Header  |  1992-09-07  |  44KB  |  1,747 lines

  1. /*
  2.  *                     RCS stream editor
  3.  */
  4. /**********************************************************************************
  5.  *                       edits the input file according to a
  6.  *                       script from stdin, generated by diff -n
  7.  *                       performs keyword expansion
  8.  **********************************************************************************
  9.  */
  10.  
  11. /* Copyright (C) 1982, 1988, 1989 Walter Tichy
  12.    Copyright 1990, 1991, 1992 by Paul Eggert
  13.    Distributed under license by the Free Software Foundation, Inc.
  14.  
  15. This file is part of RCS.
  16.  
  17. RCS is free software; you can redistribute it and/or modify
  18. it under the terms of the GNU General Public License as published by
  19. the Free Software Foundation; either version 2, or (at your option)
  20. any later version.
  21.  
  22. RCS is distributed in the hope that it will be useful,
  23. but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  25. GNU General Public License for more details.
  26.  
  27. You should have received a copy of the GNU General Public License
  28. along with RCS; see the file COPYING.  If not, write to
  29. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  30.  
  31. Report problems and direct all questions to:
  32.  
  33.     rcs-bugs@cs.purdue.edu
  34.  
  35. */
  36.  
  37.  
  38. /* $Log: rcsedit.c,v $
  39.  * Revision 5.15  1992/07/28  16:12:44  eggert
  40.  * Some hosts have readlink but not ELOOP.  Avoid `unsigned'.
  41.  * Preserve dates more systematically.  Statement macro names now end in _.
  42.  *
  43.  * Revision 5.14  1992/02/17  23:02:24  eggert
  44.  * Add -T support.
  45.  *
  46.  * Revision 5.13  1992/01/24  18:44:19  eggert
  47.  * Add support for bad_chmod_close, bad_creat0.
  48.  *
  49.  * Revision 5.12  1992/01/06  02:42:34  eggert
  50.  * Add setmode parameter to chnamemod.  addsymbol now reports changes.
  51.  * while (E) ; -> while (E) continue;
  52.  *
  53.  * Revision 5.11  1991/11/03  01:11:44  eggert
  54.  * Move the warning about link breaking to where they're actually being broken.
  55.  *
  56.  * Revision 5.10  1991/10/07  17:32:46  eggert
  57.  * Support piece tables even if !has_mmap.  Fix rare NFS bugs.
  58.  *
  59.  * Revision 5.9  1991/09/17  19:07:40  eggert
  60.  * SGI readlink() yields ENXIO, not EINVAL, for nonlinks.
  61.  *
  62.  * Revision 5.8  1991/08/19  03:13:55  eggert
  63.  * Add piece tables, NFS bug workarounds.  Catch odd filenames.  Tune.
  64.  *
  65.  * Revision 5.7  1991/04/21  11:58:21  eggert
  66.  * Fix errno bugs.  Add -x, RCSINIT, MS-DOS support.
  67.  *
  68.  * Revision 5.6  1991/02/25  07:12:40  eggert
  69.  * Fix setuid bug.  Support new link behavior.  Work around broken "w+" fopen.
  70.  *
  71.  * Revision 5.5  1990/12/30  05:07:35  eggert
  72.  * Fix report of busy RCS files when !defined(O_CREAT) | !defined(O_EXCL).
  73.  *
  74.  * Revision 5.4  1990/11/01  05:03:40  eggert
  75.  * Permit arbitrary data in comment leaders.
  76.  *
  77.  * Revision 5.3  1990/09/11  02:41:13  eggert
  78.  * Tune expandline().
  79.  *
  80.  * Revision 5.2  1990/09/04  08:02:21  eggert
  81.  * Count RCS lines better.  Improve incomplete line handling.
  82.  *
  83.  * Revision 5.1  1990/08/29  07:13:56  eggert
  84.  * Add -kkvl.
  85.  * Fix bug when getting revisions to files ending in incomplete lines.
  86.  * Fix bug in comment leader expansion.
  87.  *
  88.  * Revision 5.0  1990/08/22  08:12:47  eggert
  89.  * Don't require final newline.
  90.  * Don't append "checked in with -k by " to logs,
  91.  * so that checking in a program with -k doesn't change it.
  92.  * Don't generate trailing white space for empty comment leader.
  93.  * Remove compile-time limits; use malloc instead.  Add -k, -V.
  94.  * Permit dates past 1999/12/31.  Make lock and temp files faster and safer.
  95.  * Ansify and Posixate.  Check diff's output.
  96.  *
  97.  * Revision 4.8  89/05/01  15:12:35  narten
  98.  * changed copyright header to reflect current distribution rules
  99.  * 
  100.  * Revision 4.7  88/11/08  13:54:14  narten
  101.  * misplaced semicolon caused infinite loop
  102.  * 
  103.  * Revision 4.6  88/08/09  19:12:45  eggert
  104.  * Shrink stdio code size; allow cc -R.
  105.  * 
  106.  * Revision 4.5  87/12/18  11:38:46  narten
  107.  * Changes from the 43. version. Don't know the significance of the
  108.  * first change involving "rewind". Also, additional "lint" cleanup.
  109.  * (Guy Harris)
  110.  * 
  111.  * Revision 4.4  87/10/18  10:32:21  narten
  112.  * Updating version numbers. Changes relative to version 1.1 actually
  113.  * relative to 4.1
  114.  * 
  115.  * Revision 1.4  87/09/24  13:59:29  narten
  116.  * Sources now pass through lint (if you ignore printf/sprintf/fprintf 
  117.  * warnings)
  118.  * 
  119.  * Revision 1.3  87/09/15  16:39:39  shepler
  120.  * added an initializatin of the variables editline and linecorr
  121.  * this will be done each time a file is processed.
  122.  * (there was an obscure bug where if co was used to retrieve multiple files
  123.  *  it would dump)
  124.  * fix attributed to  Roy Morris @FileNet Corp ...!felix!roy
  125.  * 
  126.  * Revision 1.2  87/03/27  14:22:17  jenkins
  127.  * Port to suns
  128.  * 
  129.  * Revision 4.1  83/05/12  13:10:30  wft
  130.  * Added new markers Id and RCSfile; added locker to Header and Id.
  131.  * Overhauled expandline completely() (problem with $01234567890123456789@).
  132.  * Moved trymatch() and marker table to rcskeys.c.
  133.  * 
  134.  * Revision 3.7  83/05/12  13:04:39  wft
  135.  * Added retry to expandline to resume after failed match which ended in $.
  136.  * Fixed truncation problem for $19chars followed by@@.
  137.  * Log no longer expands full path of RCS file.
  138.  * 
  139.  * Revision 3.6  83/05/11  16:06:30  wft
  140.  * added retry to expandline to resume after failed match which ended in $.
  141.  * Fixed truncation problem for $19chars followed by@@.
  142.  * 
  143.  * Revision 3.5  82/12/04  13:20:56  wft
  144.  * Added expansion of keyword Locker.
  145.  *
  146.  * Revision 3.4  82/12/03  12:26:54  wft
  147.  * Added line number correction in case editing does not start at the
  148.  * beginning of the file.
  149.  * Changed keyword expansion to always print a space before closing KDELIM;
  150.  * Expansion for Header shortened.
  151.  *
  152.  * Revision 3.3  82/11/14  14:49:30  wft
  153.  * removed Suffix from keyword expansion. Replaced fclose with ffclose.
  154.  * keyreplace() gets log message from delta, not from curlogmsg.
  155.  * fixed expression overflow in while(c=putc(GETC....
  156.  * checked nil printing.
  157.  *
  158.  * Revision 3.2  82/10/18  21:13:39  wft
  159.  * I added checks for write errors during the co process, and renamed
  160.  * expandstring() to xpandstring().
  161.  *
  162.  * Revision 3.1  82/10/13  15:52:55  wft
  163.  * changed type of result of getc() from char to int.
  164.  * made keyword expansion loop in expandline() portable to machines
  165.  * without sign-extension.
  166.  */
  167.  
  168.  
  169. #include "rcsbase.h"
  170.  
  171. libId(editId, "$Id: rcsedit.c,v 5.15 1992/07/28 16:12:44 eggert Exp $")
  172.  
  173. static void keyreplace P((enum markers,struct hshentry const*,FILE*,int));
  174.  
  175. FILE *fcopy;         /* result file descriptor                */
  176. char const *resultname;     /* result pathname                    */
  177. int locker_expansion;     /* should the locker name be appended to Id val?   */
  178. #if !large_memory
  179.     static RILE *fedit; /* edit file descriptor */
  180.     static char const *editname; /* edit pathname */
  181. #endif
  182. static long editline; /* edit line counter; #lines before cursor   */
  183. static long linecorr; /* #adds - #deletes in each edit run.            */
  184.                /*used to correct editline in case file is not rewound after */
  185.                /* applying one delta                                        */
  186.  
  187. /* indexes into dirtpname */
  188. #define lockdirtp_index 0
  189. #define newRCSdirtp_index bad_creat0
  190. #define newworkdirtp_index (newRCSdirtp_index+1)
  191. #define DIRTEMPNAMES (newworkdirtp_index + 1)
  192.  
  193. enum maker {notmade, real, effective};
  194. struct buf dirtpname[DIRTEMPNAMES];        /* unlink these when done */
  195. static enum maker volatile dirtpmaker[DIRTEMPNAMES];    /* if these are set */
  196. #define lockname (dirtpname[lockdirtp_index].string)
  197. #define newRCSname (dirtpname[newRCSdirtp_index].string)
  198.  
  199.  
  200. #if has_NFS || bad_unlink
  201.     int
  202. un_link(s)
  203.     char const *s;
  204. /*
  205.  * Remove S, even if it is unwritable.
  206.  * Ignore unlink() ENOENT failures; NFS generates bogus ones.
  207.  */
  208. {
  209. #    if bad_unlink
  210.         int e;
  211.         if (unlink(s) == 0)
  212.             return 0;
  213.         e = errno;
  214. #        if has_NFS
  215.             if (e == ENOENT)
  216.                 return 0;
  217. #        endif
  218.         if (chmod(s, S_IWUSR) != 0) {
  219.             errno = e;
  220.             return -1;
  221.         }
  222. #    endif
  223. #    if has_NFS
  224.         return unlink(s)==0 || errno==ENOENT  ?  0  :  -1;
  225. #    else
  226.         return unlink(s);
  227. #    endif
  228. }
  229. #endif
  230.  
  231. #if !has_rename
  232. #  if !has_NFS
  233. #    define do_link(s,t) link(s,t)
  234. #  else
  235.     static int
  236. do_link(s, t)
  237.     char const *s, *t;
  238. /* Link S to T, ignoring bogus EEXIST problems due to NFS failures.  */
  239. {
  240.     struct stat sb, tb;
  241.  
  242.     if (link(s,t) == 0)
  243.         return 0;
  244.     if (errno != EEXIST)
  245.         return -1;
  246.     if (
  247.         stat(s, &sb) == 0  &&
  248.         stat(t, &tb) == 0  &&
  249.         same_file(sb, tb, 0)
  250.     )
  251.         return 0;
  252.     errno = EEXIST;
  253.     return -1;
  254. }
  255. #  endif
  256. #endif
  257.  
  258.  
  259.     static exiting void
  260. editEndsPrematurely()
  261. {
  262.     fatserror("edit script ends prematurely");
  263. }
  264.  
  265.     static exiting void
  266. editLineNumberOverflow()
  267. {
  268.     fatserror("edit script refers to line past end of file");
  269. }
  270.  
  271.  
  272. #if large_memory
  273.  
  274. #if has_memmove
  275. #    define movelines(s1, s2, n) VOID memmove(s1, s2, (n)*sizeof(Iptr_type))
  276. #else
  277.     static void
  278. movelines(s1, s2, n)
  279.     register Iptr_type *s1;
  280.     register Iptr_type const *s2;
  281.     register long n;
  282. {
  283.     if (s1 < s2)
  284.         do {
  285.             *s1++ = *s2++;
  286.         } while (--n);
  287.     else {
  288.         s1 += n;
  289.         s2 += n;
  290.         do {
  291.             *--s1 = *--s2;
  292.         } while (--n);
  293.     }
  294. }
  295. #endif
  296.  
  297. /*
  298.  * `line' contains pointers to the lines in the currently `edited' file.
  299.  * It is a 0-origin array that represents linelim-gapsize lines.
  300.  * line[0 .. gap-1] and line[gap+gapsize .. linelim-1] hold pointers to lines.
  301.  * line[gap .. gap+gapsize-1] contains garbage.
  302.  *
  303.  * Any @s in lines are duplicated.
  304.  * Lines are terminated by \n, or (for a last partial line only) by single @.
  305.  */
  306. static Iptr_type *line;
  307. static size_t gap, gapsize, linelim;
  308.  
  309.  
  310.     static void
  311. insertline(n, l)
  312.     long n;
  313.     Iptr_type l;
  314. /* Before line N, insert line L.  N is 0-origin.  */
  315. {
  316.     if (linelim-gapsize < n)
  317.         editLineNumberOverflow();
  318.     if (!gapsize)
  319.         line =
  320.         !linelim ?
  321.             tnalloc(Iptr_type, linelim = gapsize = 1024)
  322.         : (
  323.             gap = gapsize = linelim,
  324.             trealloc(Iptr_type, line, linelim <<= 1)
  325.         );
  326.     if (n < gap)
  327.         movelines(line+n+gapsize, line+n, gap-n);
  328.     else if (gap < n)
  329.         movelines(line+gap, line+gap+gapsize, n-gap);
  330.  
  331.     line[n] = l;
  332.     gap = n + 1;
  333.     gapsize--;
  334. }
  335.  
  336.     static void
  337. deletelines(n, nlines)
  338.     long n, nlines;
  339. /* Delete lines N through N+NLINES-1.  N is 0-origin.  */
  340. {
  341.     long l = n + nlines;
  342.     if (linelim-gapsize < l  ||  l < n)
  343.         editLineNumberOverflow();
  344.     if (l < gap)
  345.         movelines(line+l+gapsize, line+l, gap-l);
  346.     else if (gap < n)
  347.         movelines(line+gap, line+gap+gapsize, n-gap);
  348.  
  349.     gap = n;
  350.     gapsize += nlines;
  351. }
  352.  
  353.     static void
  354. snapshotline(f, l)
  355.     register FILE *f;
  356.     register Iptr_type l;
  357. {
  358.     register int c;
  359.     do {
  360.         if ((c = *l++) == SDELIM  &&  *l++ != SDELIM)
  361.             return;
  362.         aputc_(c, f)
  363.     } while (c != '\n');
  364. }
  365.  
  366.     void
  367. snapshotedit(f)
  368.     FILE *f;
  369. /* Copy the current state of the edits to F.  */
  370. {
  371.     register Iptr_type *p, *lim, *l=line;
  372.     for (p=l, lim=l+gap;  p<lim;  )
  373.         snapshotline(f, *p++);
  374.     for (p+=gapsize, lim=l+linelim;  p<lim;  )
  375.         snapshotline(f, *p++);
  376. }
  377.  
  378.     static void
  379. finisheditline(fin, fout, l, delta)
  380.     RILE *fin;
  381.     FILE *fout;
  382.     Iptr_type l;
  383.     struct hshentry const *delta;
  384. {
  385.     Iseek(fin, l);
  386.     if (expandline(fin, fout, delta, true, (FILE*)0, true)  <  0)
  387.         faterror("finisheditline internal error");
  388. }
  389.  
  390.     void
  391. finishedit(delta, outfile, done)
  392.     struct hshentry const *delta;
  393.     FILE *outfile;
  394.     int done;
  395. /*
  396.  * Doing expansion if DELTA is set, output the state of the edits to OUTFILE.
  397.  * But do nothing unless DONE is set (which means we are on the last pass).
  398.  */
  399. {
  400.     if (done) {
  401.         openfcopy(outfile);
  402.         outfile = fcopy;
  403.         if (!delta)
  404.             snapshotedit(outfile);
  405.         else {
  406.             register Iptr_type *p, *lim, *l = line;
  407.             register RILE *fin = finptr;
  408.             Iptr_type here = Itell(fin);
  409.             for (p=l, lim=l+gap;  p<lim;  )
  410.                 finisheditline(fin, outfile, *p++, delta);
  411.             for (p+=gapsize, lim=l+linelim;  p<lim;  )
  412.                 finisheditline(fin, outfile, *p++, delta);
  413.             Iseek(fin, here);
  414.         }
  415.     }
  416. }
  417.  
  418. /* Open a temporary NAME for output, truncating any previous contents.  */
  419. #   define fopen_update_truncate(name) fopen(name, FOPEN_W_WORK)
  420. #else /* !large_memory */
  421.     static FILE *
  422. fopen_update_truncate(name)
  423.     char const *name;
  424. {
  425. #    if bad_fopen_wplus
  426.         if (un_link(name) != 0)
  427.             efaterror(name);
  428. #    endif
  429.     return fopen(name, FOPEN_WPLUS_WORK);
  430. }
  431. #endif
  432.  
  433.  
  434.     void
  435. openfcopy(f)
  436.     FILE *f;
  437. {
  438.     if (!(fcopy = f)) {
  439.         if (!resultname)
  440.             resultname = maketemp(2);
  441.         if (!(fcopy = fopen_update_truncate(resultname)))
  442.             efaterror(resultname);
  443.     }
  444. }
  445.  
  446.  
  447. #if !large_memory
  448.  
  449.     static void
  450. swapeditfiles(outfile)
  451.     FILE *outfile;
  452. /* Function: swaps resultname and editname, assigns fedit=fcopy,
  453.  * and rewinds fedit for reading.  Set fcopy to outfile if nonnull;
  454.  * otherwise, set fcopy to be resultname opened for reading and writing.
  455.  */
  456. {
  457.     char const *tmpptr;
  458.  
  459.     editline = 0;  linecorr = 0;
  460.     if (fseek(fcopy, 0L, SEEK_SET) != 0)
  461.         Oerror();
  462.     fedit = fcopy;
  463.     tmpptr=editname; editname=resultname; resultname=tmpptr;
  464.     openfcopy(outfile);
  465. }
  466.  
  467.     void
  468. snapshotedit(f)
  469.     FILE *f;
  470. /* Copy the current state of the edits to F.  */
  471. {
  472.     finishedit((struct hshentry *)nil, (FILE*)0, false);
  473.     fastcopy(fedit, f);
  474.     Irewind(fedit);
  475. }
  476.  
  477.     void
  478. finishedit(delta, outfile, done)
  479.     struct hshentry const *delta;
  480.     FILE *outfile;
  481.     int done;
  482. /* copy the rest of the edit file and close it (if it exists).
  483.  * if delta!=nil, perform keyword substitution at the same time.
  484.  * If DONE is set, we are finishing the last pass.
  485.  */
  486. {
  487.     register RILE *fe;
  488.     register FILE *fc;
  489.  
  490.     fe = fedit;
  491.     if (fe) {
  492.         fc = fcopy;
  493.                 if (delta!=nil) {
  494.             while (1 < expandline(fe,fc,delta,false,(FILE*)0,true))
  495.                 ;
  496.                 } else {
  497.             fastcopy(fe,fc);
  498.                 }
  499.         Ifclose(fe);
  500.         }
  501.     if (!done)
  502.         swapeditfiles(outfile);
  503. }
  504. #endif
  505.  
  506.  
  507.  
  508. #if large_memory
  509. #    define copylines(upto,delta) (editline = (upto))
  510. #else
  511.     static void
  512. copylines(upto,delta)
  513.     register long upto;
  514.     struct hshentry const *delta;
  515. /*
  516.  * Copy input lines editline+1..upto from fedit to fcopy.
  517.  * If delta != nil, keyword expansion is done simultaneously.
  518.  * editline is updated. Rewinds a file only if necessary.
  519.  */
  520. {
  521.     register int c;
  522.     declarecache;
  523.     register FILE *fc;
  524.     register RILE *fe;
  525.  
  526.     if (upto < editline) {
  527.                 /* swap files */
  528.         finishedit((struct hshentry *)nil, (FILE*)0, false);
  529.                 /* assumes edit only during last pass, from the beginning*/
  530.         }
  531.     fe = fedit;
  532.     fc = fcopy;
  533.     if (editline < upto)
  534.         if (delta)
  535.         do {
  536.             if (expandline(fe,fc,delta,false,(FILE*)0,true) <= 1)
  537.                 editLineNumberOverflow();
  538.         } while (++editline < upto);
  539.         else {
  540.         setupcache(fe); cache(fe);
  541.         do {
  542.             do {
  543.                 cachegeteof_(c, editLineNumberOverflow();)
  544.                 aputc_(c, fc)
  545.             } while (c != '\n');
  546.         } while (++editline < upto);
  547.         uncache(fe);
  548.         }
  549. }
  550. #endif
  551.  
  552.  
  553.  
  554.     void
  555. xpandstring(delta)
  556.     struct hshentry const *delta;
  557. /* Function: Reads a string terminated by SDELIM from finptr and writes it
  558.  * to fcopy. Double SDELIM is replaced with single SDELIM.
  559.  * Keyword expansion is performed with data from delta.
  560.  * If foutptr is nonnull, the string is also copied unchanged to foutptr.
  561.  */
  562. {
  563.     while (1 < expandline(finptr,fcopy,delta,true,foutptr,true))
  564.         continue;
  565. }
  566.  
  567.  
  568.     void
  569. copystring()
  570. /* Function: copies a string terminated with a single SDELIM from finptr to
  571.  * fcopy, replacing all double SDELIM with a single SDELIM.
  572.  * If foutptr is nonnull, the string also copied unchanged to foutptr.
  573.  * editline is incremented by the number of lines copied.
  574.  * Assumption: next character read is first string character.
  575.  */
  576. {    register c;
  577.     declarecache;
  578.     register FILE *frew, *fcop;
  579.     register int amidline;
  580.     register RILE *fin;
  581.  
  582.     fin = finptr;
  583.     setupcache(fin); cache(fin);
  584.     frew = foutptr;
  585.     fcop = fcopy;
  586.     amidline = false;
  587.     for (;;) {
  588.         GETC_(frew,c)
  589.         switch (c) {
  590.             case '\n':
  591.             ++editline;
  592.             ++rcsline;
  593.             amidline = false;
  594.             break;
  595.             case SDELIM:
  596.             GETC_(frew,c)
  597.             if (c != SDELIM) {
  598.                 /* end of string */
  599.                 nextc = c;
  600.                 editline += amidline;
  601.                 uncache(fin);
  602.                 return;
  603.             }
  604.             /* fall into */
  605.             default:
  606.             amidline = true;
  607.             break;
  608.                 }
  609.         aputc_(c,fcop)
  610.         }
  611. }
  612.  
  613.  
  614.     void
  615. enterstring()
  616. /* Like copystring, except the string is put into the edit data structure.  */
  617. {
  618. #if !large_memory
  619.     editname = 0;
  620.     fedit = 0;
  621.     editline = linecorr = 0;
  622.     resultname = maketemp(1);
  623.     if (!(fcopy = fopen_update_truncate(resultname)))
  624.         efaterror(resultname);
  625.     copystring();
  626. #else
  627.     register int c;
  628.     declarecache;
  629.     register FILE *frew;
  630.     register long e, oe;
  631.     register int amidline, oamidline;
  632.     register Iptr_type optr;
  633.     register RILE *fin;
  634.  
  635.     e = 0;
  636.     gap = 0;
  637.     gapsize = linelim;
  638.     fin = finptr;
  639.     setupcache(fin); cache(fin);
  640.     advise_access(fin, MADV_NORMAL);
  641.     frew = foutptr;
  642.     amidline = false;
  643.     for (;;) {
  644.         optr = cachetell();
  645.         GETC_(frew,c)
  646.         oamidline = amidline;
  647.         oe = e;
  648.         switch (c) {
  649.             case '\n':
  650.             ++e;
  651.             ++rcsline;
  652.             amidline = false;
  653.             break;
  654.             case SDELIM:
  655.             GETC_(frew,c)
  656.             if (c != SDELIM) {
  657.                 /* end of string */
  658.                 nextc = c;
  659.                 editline = e + amidline;
  660.                 linecorr = 0;
  661.                 uncache(fin);
  662.                 return;
  663.             }
  664.             /* fall into */
  665.             default:
  666.             amidline = true;
  667.             break;
  668.         }
  669.         if (!oamidline)
  670.             insertline(oe, optr);
  671.     }
  672. #endif
  673. }
  674.  
  675.  
  676.  
  677.  
  678.     void
  679. #if large_memory
  680. edit_string()
  681. #else
  682.   editstring(delta)
  683.     struct hshentry const *delta;
  684. #endif
  685. /*
  686.  * Read an edit script from finptr and applies it to the edit file.
  687. #if !large_memory
  688.  * The result is written to fcopy.
  689.  * If delta!=nil, keyword expansion is performed simultaneously.
  690.  * If running out of lines in fedit, fedit and fcopy are swapped.
  691.  * editname is the name of the file that goes with fedit.
  692. #endif
  693.  * If foutptr is set, the edit script is also copied verbatim to foutptr.
  694.  * Assumes that all these files are open.
  695.  * resultname is the name of the file that goes with fcopy.
  696.  * Assumes the next input character from finptr is the first character of
  697.  * the edit script. Resets nextc on exit.
  698.  */
  699. {
  700.         int ed; /* editor command */
  701.         register int c;
  702.     declarecache;
  703.     register FILE *frew;
  704. #    if !large_memory
  705.         register FILE *f;
  706.         long line_lim = LONG_MAX;
  707.         register RILE *fe;
  708. #    endif
  709.     register long i;
  710.     register RILE *fin;
  711. #    if large_memory
  712.         register long j;
  713. #    endif
  714.     struct diffcmd dc;
  715.  
  716.         editline += linecorr; linecorr=0; /*correct line number*/
  717.     frew = foutptr;
  718.     fin = finptr;
  719.     setupcache(fin);
  720.     initdiffcmd(&dc);
  721.     while (0  <=  (ed = getdiffcmd(fin,true,frew,&dc)))
  722. #if !large_memory
  723.         if (line_lim <= dc.line1)
  724.             editLineNumberOverflow();
  725.         else
  726. #endif
  727.         if (!ed) {
  728.             copylines(dc.line1-1, delta);
  729.                         /* skip over unwanted lines */
  730.             i = dc.nlines;
  731.             linecorr -= i;
  732.             editline += i;
  733. #            if large_memory
  734.                 deletelines(editline+linecorr, i);
  735. #            else
  736.                 fe = fedit;
  737.                 do {
  738.                                 /*skip next line*/
  739.                 do {
  740.                     Igeteof_(fe, c, { if (i!=1) editLineNumberOverflow(); line_lim = dc.dafter; break; } )
  741.                 } while (c != '\n');
  742.                 } while (--i);
  743. #            endif
  744.         } else {
  745.             copylines(dc.line1, delta); /*copy only; no delete*/
  746.             i = dc.nlines;
  747. #            if large_memory
  748.                 j = editline+linecorr;
  749. #            endif
  750.             linecorr += i;
  751. #if !large_memory
  752.             f = fcopy;
  753.             if (delta)
  754.                 do {
  755.                 switch (expandline(fin,f,delta,true,frew,true)){
  756.                     case 0: case 1:
  757.                     if (i==1)
  758.                         return;
  759.                     /* fall into */
  760.                     case -1:
  761.                     editEndsPrematurely();
  762.                 }
  763.                 } while (--i);
  764.             else
  765. #endif
  766.             {
  767.                 cache(fin);
  768.                 do {
  769. #                if large_memory
  770.                     insertline(j++, cachetell());
  771. #                endif
  772.                 for (;;) {
  773.                     GETC_(frew, c)
  774. #                    if !large_memory
  775.                     aputc_(c, f)
  776. #                    endif
  777.                     if (c == '\n')
  778.                     break;
  779.                     if (c==SDELIM) {
  780.                     GETC_(frew, c)
  781.                     if (c!=SDELIM) {
  782.                         if (--i)
  783.                         editEndsPrematurely();
  784.                         nextc = c;
  785.                         uncache(fin);
  786.                         return;
  787.                     }
  788.                     }
  789.                 }
  790.                 ++rcsline;
  791.                 } while (--i);
  792.                 uncache(fin);
  793.             }
  794.                 }
  795. }
  796.  
  797.  
  798.  
  799. /* The rest is for keyword expansion */
  800.  
  801.  
  802.  
  803.     int
  804. expandline(infile, outfile, delta, delimstuffed, frewfile, dolog)
  805.     RILE *infile;
  806.     FILE *outfile, *frewfile;
  807.     struct hshentry const *delta;
  808.     int delimstuffed, dolog;
  809. /*
  810.  * Read a line from INFILE and write it to OUTFILE.
  811.  * Do keyword expansion with data from DELTA.
  812.  * If DELIMSTUFFED is true, double SDELIM is replaced with single SDELIM.
  813.  * If FREWFILE is set, copy the line unchanged to FREWFILE.
  814.  * DELIMSTUFFED must be true if FREWFILE is set.
  815.  * Append revision history to log only if DOLOG is set.
  816.  * Yields -1 if no data is copied, 0 if an incomplete line is copied,
  817.  * 2 if a complete line is copied; adds 1 to yield if expansion occurred.
  818.  */
  819. {
  820.     register c;
  821.     declarecache;
  822.     register FILE *out, *frew;
  823.     register char * tp;
  824.     register int e, ds, r;
  825.     char const *tlim;
  826.     static struct buf keyval;
  827.         enum markers matchresult;
  828.  
  829.     setupcache(infile); cache(infile);
  830.     out = outfile;
  831.     frew = frewfile;
  832.     ds = delimstuffed;
  833.     bufalloc(&keyval, keylength+3);
  834.     e = 0;
  835.     r = -1;
  836.  
  837.         for (;;) {
  838.         if (ds)
  839.         GETC_(frew, c)
  840.         else
  841.         cachegeteof_(c, goto uncache_exit;)
  842.         for (;;) {
  843.         switch (c) {
  844.             case SDELIM:
  845.             if (ds) {
  846.                 GETC_(frew, c)
  847.                 if (c != SDELIM) {
  848.                                 /* end of string */
  849.                                 nextc=c;
  850.                 goto uncache_exit;
  851.                 }
  852.             }
  853.             /* fall into */
  854.             default:
  855.             aputc_(c,out)
  856.             r = 0;
  857.             break;
  858.  
  859.             case '\n':
  860.             rcsline += ds;
  861.             aputc_(c,out)
  862.             r = 2;
  863.             goto uncache_exit;
  864.  
  865.             case KDELIM:
  866.             r = 0;
  867.                         /* check for keyword */
  868.                         /* first, copy a long enough string into keystring */
  869.             tp = keyval.string;
  870.             *tp++ = KDELIM;
  871.             for (;;) {
  872.                 if (ds)
  873.                 GETC_(frew, c)
  874.                 else
  875.                 cachegeteof_(c, goto keystring_eof;)
  876.                 if (tp < keyval.string+keylength+1)
  877.                 switch (ctab[c]) {
  878.                     case LETTER: case Letter:
  879.                     *tp++ = c;
  880.                     continue;
  881.                     default:
  882.                     break;
  883.                 }
  884.                 break;
  885.                         }
  886.             *tp++ = c; *tp = '\0';
  887.             matchresult = trymatch(keyval.string+1);
  888.             if (matchresult==Nomatch) {
  889.                 tp[-1] = 0;
  890.                 aputs(keyval.string, out);
  891.                 continue;   /* last c handled properly */
  892.             }
  893.  
  894.             /* Now we have a keyword terminated with a K/VDELIM */
  895.             if (c==VDELIM) {
  896.                   /* try to find closing KDELIM, and replace value */
  897.                   tlim = keyval.string + keyval.size;
  898.                   for (;;) {
  899.                       if (ds)
  900.                     GETC_(frew, c)
  901.                       else
  902.                     cachegeteof_(c, goto keystring_eof;)
  903.                       if (c=='\n' || c==KDELIM)
  904.                     break;
  905.                       *tp++ =c;
  906.                       if (tlim <= tp)
  907.                       tp = bufenlarge(&keyval, &tlim);
  908.                       if (c==SDELIM && ds) { /*skip next SDELIM */
  909.                         GETC_(frew, c)
  910.                         if (c != SDELIM) {
  911.                             /* end of string before closing KDELIM or newline */
  912.                             nextc = c;
  913.                             goto keystring_eof;
  914.                         }
  915.                       }
  916.                   }
  917.                   if (c!=KDELIM) {
  918.                     /* couldn't find closing KDELIM -- give up */
  919.                     *tp = 0;
  920.                     aputs(keyval.string, out);
  921.                     continue;   /* last c handled properly */
  922.                   }
  923.             }
  924.             /* now put out the new keyword value */
  925.             keyreplace(matchresult, delta, out, dolog);
  926.             e = 1;
  927.             break;
  928.                 }
  929.         break;
  930.         }
  931.         }
  932.  
  933.     keystring_eof:
  934.     *tp = 0;
  935.     aputs(keyval.string, out);
  936.     uncache_exit:
  937.     uncache(infile);
  938.     return r + e;
  939. }
  940.  
  941.  
  942. char const ciklog[ciklogsize] = "checked in with -k by ";
  943.  
  944.     static void
  945. keyreplace(marker, delta, out, dolog)
  946.     enum markers marker;
  947.     register struct hshentry const *delta;
  948.     register FILE *out;
  949.     int dolog;
  950. /* function: outputs the keyword value(s) corresponding to marker.
  951.  * Attributes are derived from delta.
  952.  */
  953. {
  954.     register char const *sp, *cp, *date;
  955.     register char c;
  956.     register size_t cs, cw, ls;
  957.     char const *sp1;
  958.     char datebuf[datesize];
  959.     int RCSv;
  960.  
  961.     sp = Keyword[(int)marker];
  962.  
  963.     if (Expand == KEY_EXPAND) {
  964.         aprintf(out, "%c%s%c", KDELIM, sp, KDELIM);
  965.         return;
  966.     }
  967.  
  968.         date= delta->date;
  969.     RCSv = RCSversion;
  970.  
  971.     if (Expand == KEYVAL_EXPAND  ||  Expand == KEYVALLOCK_EXPAND)
  972.         aprintf(out, "%c%s%c%c", KDELIM, sp, VDELIM,
  973.             marker==Log && RCSv<VERSION(5)  ?  '\t'  :  ' '
  974.         );
  975.  
  976.         switch (marker) {
  977.         case Author:
  978.         aputs(delta->author, out);
  979.                 break;
  980.         case Date:
  981.         aputs(date2str(date,datebuf), out);
  982.                 break;
  983.         case Id:
  984.     case Header:
  985.         aprintf(out, "%s %s %s %s %s",
  986.               marker==Id || RCSv<VERSION(4)
  987.             ? basename(RCSname)
  988.             : getfullRCSname(),
  989.             delta->num,
  990.             date2str(date, datebuf),
  991.             delta->author,
  992.               RCSv==VERSION(3) && delta->lockedby ? "Locked"
  993.             : delta->state
  994.         );
  995.         if (delta->lockedby!=nil)
  996.             if (VERSION(5) <= RCSv) {
  997.             if (locker_expansion || Expand==KEYVALLOCK_EXPAND)
  998.                 aprintf(out, " %s", delta->lockedby);
  999.             } else if (RCSv == VERSION(4))
  1000.             aprintf(out, " Locker: %s", delta->lockedby);
  1001.                 break;
  1002.         case Locker:
  1003.         if (delta->lockedby)
  1004.             if (
  1005.                 locker_expansion
  1006.             ||    Expand == KEYVALLOCK_EXPAND
  1007.             ||    RCSv <= VERSION(4)
  1008.             )
  1009.             aputs(delta->lockedby, out);
  1010.                 break;
  1011.         case Log:
  1012.         case RCSfile:
  1013.         aputs(basename(RCSname), out);
  1014.                 break;
  1015.         case Revision:
  1016.         aputs(delta->num, out);
  1017.                 break;
  1018.         case Source:
  1019.         aputs(getfullRCSname(), out);
  1020.                 break;
  1021.         case State:
  1022.         aputs(delta->state, out);
  1023.                 break;
  1024.     default:
  1025.         break;
  1026.         }
  1027.     if (Expand == KEYVAL_EXPAND  ||  Expand == KEYVALLOCK_EXPAND) {
  1028.         afputc(' ', out);
  1029.         afputc(KDELIM, out);
  1030.     }
  1031.     if (marker == Log   &&  dolog) {
  1032.         sp = delta->log.string;
  1033.         ls = delta->log.size;
  1034.         if (sizeof(ciklog)-1<=ls && !memcmp(sp,ciklog,sizeof(ciklog)-1))
  1035.             return;
  1036.         afputc('\n', out);
  1037.         cp = Comment.string;
  1038.         cw = cs = Comment.size;
  1039.         awrite(cp, cs, out);
  1040.         /* oddity: 2 spaces between date and time, not 1 as usual */
  1041.         sp1 = strchr(date2str(date,datebuf), ' ');
  1042.         aprintf(out, "Revision %s  %.*s %s  %s",
  1043.             delta->num, (int)(sp1-datebuf), datebuf, sp1, delta->author
  1044.         );
  1045.         /* Do not include state: it may change and is not updated.  */
  1046.         /* Comment is the comment leader.  */
  1047.         if (VERSION(5) <= RCSv)
  1048.             for (;  cw && (cp[cw-1]==' ' || cp[cw-1]=='\t');  --cw)
  1049.             continue;
  1050.         for (;;) {
  1051.             afputc('\n', out);
  1052.             awrite(cp, cw, out);
  1053.             if (!ls)
  1054.             break;
  1055.             --ls;
  1056.             c = *sp++;
  1057.             if (c != '\n') {
  1058.             awrite(cp+cw, cs-cw, out);
  1059.             do {
  1060.                 afputc(c,out);
  1061.                 if (!ls)
  1062.                 break;
  1063.                 --ls;
  1064.                 c = *sp++;
  1065.             } while (c != '\n');
  1066.             }
  1067.         }
  1068.     }
  1069. }
  1070.  
  1071. #if has_readlink
  1072.     static int
  1073. resolve_symlink(L)
  1074.     struct buf *L;
  1075. /*
  1076.  * If L is a symbolic link, resolve it to the name that it points to.
  1077.  * If unsuccessful, set errno and yield -1.
  1078.  * If it points to an existing file, yield 1.
  1079.  * Otherwise, set errno=ENOENT and yield 0.
  1080.  */
  1081. {
  1082.     char *b, a[SIZEABLE_PATH];
  1083.     int e;
  1084.     size_t s;
  1085.     ssize_t r;
  1086.     struct buf bigbuf;
  1087.     int linkcount = MAXSYMLINKS;
  1088.  
  1089.     b = a;
  1090.     s = sizeof(a);
  1091.     bufautobegin(&bigbuf);
  1092.     while ((r = readlink(L->string,b,s))  !=  -1)
  1093.         if (r == s) {
  1094.         bufalloc(&bigbuf, s<<1);
  1095.         b = bigbuf.string;
  1096.         s = bigbuf.size;
  1097.         } else if (!linkcount--) {
  1098. #        ifndef ELOOP
  1099.             /*
  1100.             * Some pedantic Posix 1003.1-1990 hosts have readlink
  1101.             * but not ELOOP.  Approximate ELOOP with EMLINK.
  1102.             */
  1103. #            define ELOOP EMLINK
  1104. #        endif
  1105.         errno = ELOOP;
  1106.         return -1;
  1107.         } else {
  1108.         /* Splice symbolic link into L.  */
  1109.         b[r] = '\0';
  1110.         L->string[ROOTPATH(b) ? (size_t)0 : dirlen(L->string)]  =  '\0';
  1111.         bufscat(L, b);
  1112.         }
  1113.     e = errno;
  1114.     bufautoend(&bigbuf);
  1115.     errno = e;
  1116.     switch (e) {
  1117.         case readlink_isreg_errno: return 1;
  1118.         case ENOENT: return 0;
  1119.         default: return -1;
  1120.     }
  1121. }
  1122. #endif
  1123.  
  1124.     RILE *
  1125. rcswriteopen(RCSbuf, status, mustread)
  1126.     struct buf *RCSbuf;
  1127.     struct stat *status;
  1128.     int mustread;
  1129. /*
  1130.  * Create the lock file corresponding to RCSBUF.
  1131.  * Then try to open RCSBUF for reading and yield its RILE* descriptor.
  1132.  * Put its status into *STATUS too.
  1133.  * MUSTREAD is true if the file must already exist, too.
  1134.  * If all goes well, discard any previously acquired locks,
  1135.  * and set fdlock to the file descriptor of the RCS lockfile.
  1136.  */
  1137. {
  1138.     register char *tp;
  1139.     register char const *sp, *RCSpath, *x;
  1140.     RILE *f;
  1141.     size_t l;
  1142.     int e, exists, fdesc, r, waslocked;
  1143.     struct buf *dirt;
  1144.     struct stat statbuf;
  1145.  
  1146.     waslocked  =  0 <= fdlock;
  1147.     exists =
  1148. #        if has_readlink
  1149.             resolve_symlink(RCSbuf);
  1150. #        else
  1151.                 stat(RCSbuf->string, &statbuf) == 0  ?  1
  1152.             :   errno==ENOENT ? 0 : -1;
  1153. #        endif
  1154.     if (exists < (mustread|waslocked))
  1155.         /*
  1156.          * There's an unusual problem with the RCS file;
  1157.          * or the RCS file doesn't exist,
  1158.          * and we must read or we already have a lock elsewhere.
  1159.          */
  1160.         return 0;
  1161.  
  1162.     RCSpath = RCSbuf->string;
  1163.     sp = basename(RCSpath);
  1164.     l = sp - RCSpath;
  1165.     dirt = &dirtpname[waslocked];
  1166.     bufscpy(dirt, RCSpath);
  1167.     tp = dirt->string + l;
  1168.     x = rcssuffix(RCSpath);
  1169. #    if has_readlink
  1170.         if (!x) {
  1171.         error("symbolic link to non RCS file `%s'", RCSpath);
  1172.         errno = EINVAL;
  1173.         return 0;
  1174.         }
  1175. #    endif
  1176.     if (*sp == *x) {
  1177.         error("RCS pathname `%s' incompatible with suffix `%s'", sp, x);
  1178.         errno = EINVAL;
  1179.         return 0;
  1180.     }
  1181.     /* Create a lock filename that is a function of the RCS filename.  */
  1182.     if (*x) {
  1183.         /*
  1184.          * The suffix is nonempty.
  1185.          * The lock filename is the first char of of the suffix,
  1186.          * followed by the RCS filename with last char removed.  E.g.:
  1187.          *    foo,v    RCS filename with suffix ,v
  1188.          *    ,foo,    lock filename
  1189.          */
  1190.         *tp++ = *x;
  1191.         while (*sp)
  1192.             *tp++ = *sp++;
  1193.         *--tp = 0;
  1194.     } else {
  1195.         /*
  1196.          * The suffix is empty.
  1197.          * The lock filename is the RCS filename
  1198.          * with last char replaced by '_'.
  1199.          */
  1200.         while ((*tp++ = *sp++))
  1201.             continue;
  1202.         tp -= 2;
  1203.         if (*tp == '_') {
  1204.             error("RCS pathname `%s' ends with `%c'", RCSpath, *tp);
  1205.             errno = EINVAL;
  1206.             return 0;
  1207.         }
  1208.         *tp = '_';
  1209.     }
  1210.  
  1211.     sp = dirt->string;
  1212.  
  1213.     f = 0;
  1214.  
  1215.     /*
  1216.     * good news:
  1217.     *    open(f, O_CREAT|O_EXCL|O_TRUNC|O_WRONLY, READONLY) is atomic
  1218.     *    according to Posix 1003.1-1990.
  1219.     * bad news:
  1220.     *    NFS ignores O_EXCL and doesn't comply with Posix 1003.1-1990.
  1221.     * good news:
  1222.     *    (O_TRUNC,READONLY) normally guarantees atomicity even with NFS.
  1223.     * bad news:
  1224.     *    If you're root, (O_TRUNC,READONLY) doesn't guarantee atomicity.
  1225.     * good news:
  1226.     *    Root-over-the-wire NFS access is rare for security reasons.
  1227.     *    This bug has never been reported in practice with RCS.
  1228.     * So we don't worry about this bug.
  1229.     *
  1230.     * An even rarer NFS bug can occur when clients retry requests,
  1231.     * which can happen (albeit rarely) in the usual case of NFS over UDP.
  1232.     * Suppose client A renames the lock file ",f," to "f,v"
  1233.     * at about the same time that client B creates ",f,",
  1234.     * and suppose A's first rename request is delayed, so A reissues it.
  1235.     * The sequence of events might be:
  1236.     *    A sends rename(",f,", "f,v")
  1237.     *    B sends create(",f,")
  1238.     *    A sends retry of rename(",f,", "f,v")
  1239.     *    server receives, does, and acknowledges A's first rename()
  1240.     *    A receives acknowledgment, and its RCS program exits
  1241.     *    server receives, does, and acknowledges B's create()
  1242.     *    server receives, does, and acknowledges A's retry of rename()
  1243.     * This not only wrongly deletes B's lock, it removes the RCS file!
  1244.     * Most NFS implementations have idempotency caches that usually prevent
  1245.     * this scenario, but such caches are finite and can be overrun.
  1246.     * This problem afflicts programs that use the traditional
  1247.     * Unix method of using link() and unlink() to get and release locks,
  1248.     * as well as RCS's method of using open() and rename().
  1249.     * There is no easy workaround for either link-unlink or open-rename.
  1250.     * Any new method based on lockf() seemingly would be incompatible with
  1251.     * the old methods; besides, lockf() is notoriously buggy under NFS.
  1252.     * Since this problem afflicts scads of Unix programs, but is so rare
  1253.     * that nobody seems to be worried about it, we won't worry either.
  1254.     */
  1255. #    define READONLY (S_IRUSR|S_IRGRP|S_IROTH)
  1256. #    if !open_can_creat
  1257. #        define create(f) creat(f, READONLY)
  1258. #    else
  1259. #if defined(__MSC__) && defined(__MSDOS__)
  1260. #include <share.h>
  1261. #define create(f) open(f, OPEN_O_BINARY|O_CREAT|O_EXCL|O_TRUNC|O_WRONLY|SH_DENYRW, S_IWRITE|S_IREAD)
  1262. #else
  1263. #        define create(f) open(f, OPEN_O_BINARY|O_CREAT|O_EXCL|O_TRUNC|O_WRONLY, READONLY)
  1264. #endif
  1265. #    endif
  1266.  
  1267.     catchints();
  1268.     ignoreints();
  1269.  
  1270.     /*
  1271.      * Create a lock file for an RCS file.  This should be atomic, i.e.
  1272.      * if two processes try it simultaneously, at most one should succeed.
  1273.      */
  1274.     seteid();
  1275.     fdesc = create(sp);
  1276.     e = errno;
  1277.     setrid();
  1278.  
  1279.     if (fdesc < 0) {
  1280.         if (e == EACCES  &&  stat(sp,&statbuf) == 0)
  1281.             /* The RCS file is busy.  */
  1282.             e = EEXIST;
  1283.     } else {
  1284.         dirtpmaker[0] = effective;
  1285.         e = ENOENT;
  1286.         if (exists) {
  1287.             f = Iopen(RCSpath, FOPEN_R, status);
  1288.             e = errno;
  1289.             if (f && waslocked) {
  1290.             /* Discard the previous lock in favor of this one.  */
  1291.             ORCSclose();
  1292.             seteid();
  1293.             r = un_link(lockname);
  1294.             e = errno;
  1295.             setrid();
  1296.             if (r != 0)
  1297.                 enfaterror(e, lockname);
  1298.             bufscpy(&dirtpname[lockdirtp_index], sp);
  1299.             }
  1300.         }
  1301.         fdlock = fdesc;
  1302.     }
  1303.  
  1304.     restoreints();
  1305.  
  1306.     errno = e;
  1307.     return f;
  1308. }
  1309.  
  1310.     void
  1311. keepdirtemp(name)
  1312.     char const *name;
  1313. /* Do not unlink name, either because it's not there any more,
  1314.  * or because it has already been unlinked.
  1315.  */
  1316. {
  1317.     register int i;
  1318.     for (i=DIRTEMPNAMES; 0<=--i; )
  1319.         if (dirtpname[i].string == name) {
  1320.             dirtpmaker[i] = notmade;
  1321.             return;
  1322.         }
  1323.     faterror("keepdirtemp");
  1324. }
  1325.  
  1326.     char const *
  1327. makedirtemp(isworkfile)
  1328.     int isworkfile;
  1329. /*
  1330.  * Create a unique pathname and store it into dirtpname.
  1331.  * Because of storage in tpnames, dirtempunlink() can unlink the file later.
  1332.  * Return a pointer to the pathname created.
  1333.  * If ISWORKFILE is 1, put it into the working file's directory;
  1334.  * if 0, put the unique file in RCSfile's directory.
  1335.  */
  1336. {
  1337.     register char *tp, *np;
  1338.     register size_t dl;
  1339.     register struct buf *bn;
  1340.     register char const *name = isworkfile ? workname : RCSname;
  1341.  
  1342.     dl = dirlen(name);
  1343.     bn = &dirtpname[newRCSdirtp_index + isworkfile];
  1344.     bufalloc(bn,
  1345. #        if has_mktemp
  1346.             dl + 9
  1347. #        else
  1348.             strlen(name) + 3
  1349. #        endif
  1350.     );
  1351.     bufscpy(bn, name);
  1352.     np = tp = bn->string;
  1353.     tp += dl;
  1354.     *tp++ = '_';
  1355.     *tp++ = '0'+isworkfile;
  1356.     catchints();
  1357. #    if has_mktemp
  1358.         VOID strcpy(tp, "XXXXXX");
  1359.         if (!mktemp(np) || !*np)
  1360.             faterror("can't make temporary pathname `%.*s_%cXXXXXX'",
  1361.             (int)dl, name, '0'+isworkfile
  1362.             );
  1363. #    else
  1364.         /*
  1365.          * Posix 1003.1-1990 has no reliable way
  1366.          * to create a unique file in a named directory.
  1367.          * We fudge here.  If the filename is abcde,
  1368.          * the temp filename is _Ncde where N is a digit.
  1369.          */
  1370.         name += dl;
  1371.         if (*name) name++;
  1372.         if (*name) name++;
  1373.         VOID strcpy(tp, name);
  1374. #    endif
  1375.     dirtpmaker[newRCSdirtp_index + isworkfile] = real;
  1376.     return np;
  1377. }
  1378.  
  1379.     void
  1380. dirtempunlink()
  1381. /* Clean up makedirtemp() files.  May be invoked by signal handler. */
  1382. {
  1383.     register int i;
  1384.     enum maker m;
  1385.  
  1386.     for (i = DIRTEMPNAMES;  0 <= --i;  )
  1387.         if ((m = dirtpmaker[i]) != notmade) {
  1388.         if (m == effective)
  1389.             seteid();
  1390.         VOID un_link(dirtpname[i].string);
  1391.         if (m == effective)
  1392.             setrid();
  1393.         dirtpmaker[i] = notmade;
  1394.         }
  1395. }
  1396.  
  1397.  
  1398.     int
  1399. #if has_prototypes
  1400. chnamemod(
  1401.     FILE **fromp, char const *from, char const *to,
  1402.     int setmode, mode_t mode, time_t mtime
  1403. )
  1404.   /* The `#if has_prototypes' is needed because mode_t might promote to int.  */
  1405. #else
  1406.   chnamemod(fromp, from, to, setmode, mode, mtime)
  1407.     FILE **fromp; char const *from,*to;
  1408.     int setmode; mode_t mode; time_t mtime;
  1409. #endif
  1410. /*
  1411.  * Rename a file (with stream pointer *FROMP) from FROM to TO.
  1412.  * FROM already exists.
  1413.  * If SETMODE is positive, change the mode to MODE, before renaming if possible.
  1414.  * If MTIME is not -1, change its mtime to TIME, before renaming if possible.
  1415.  * Close and clear *FROMP before renaming it.
  1416.  * Unlink TO if it already exists.
  1417.  * Return -1 on error (setting errno), 0 otherwise.
  1418.  */
  1419. {
  1420. #    if bad_a_rename
  1421.         /*
  1422.          * This host is brain damaged.  A race condition is possible
  1423.          * while the lock file is temporarily writable.
  1424.          * There doesn't seem to be a workaround.
  1425.          */
  1426.         mode_t mode_while_renaming;
  1427.         if (setmode <= 0) {
  1428.             struct stat st;
  1429.             if (stat(from, &st) != 0)
  1430.             return -1;
  1431.             mode = st.st_mode;
  1432.         }
  1433.         mode_while_renaming = mode|S_IWUSR;
  1434.         if (mode != mode_while_renaming)
  1435.             setmode = 1;
  1436. #    else
  1437. #        define mode_while_renaming mode
  1438. #    endif
  1439.  
  1440. #    if has_fchmod
  1441.         if (0<setmode  &&  fchmod(fileno(*fromp),mode_while_renaming) != 0)
  1442.         return -1;
  1443.         Ozclose(fromp);
  1444. #    else
  1445.         /* If bad_chmod_close, we must close before chmod.  */
  1446.         Ozclose(fromp);
  1447.         if (0<setmode  &&  chmod(from, mode_while_renaming) != 0)
  1448.         return -1;
  1449. #    endif
  1450.  
  1451.     if (setmtime(from, mtime) != 0)
  1452.         return -1;
  1453.  
  1454. #    if !has_rename || bad_b_rename
  1455.         VOID un_link(to);
  1456.         /*
  1457.          * We need not check the result;
  1458.          * link() or rename() will catch it.
  1459.          * No harm is done if TO does not exist.
  1460.          * However, there's a short window of inconsistency
  1461.          * during which TO does not exist.
  1462.          */
  1463. #    endif
  1464.  
  1465.     return
  1466. #        if !has_rename
  1467.         do_link(from,to) != 0  ?  -1  :  un_link(from)
  1468. #        else
  1469.             rename(from, to) != 0
  1470. #            if has_NFS
  1471.             && errno != ENOENT
  1472. #            endif
  1473.         ?  -1
  1474. #        if bad_a_rename
  1475.         :  0<setmode  ?  chmod(to, mode)
  1476. #        endif
  1477.         :  0
  1478. #        endif
  1479.     ;
  1480.  
  1481. #    undef mode_while_renaming
  1482. }
  1483.  
  1484.  
  1485.  
  1486.     int
  1487. findlock(delete, target)
  1488.     int delete;
  1489.     struct hshentry **target;
  1490. /*
  1491.  * Find the first lock held by caller and return a pointer
  1492.  * to the locked delta; also removes the lock if DELETE.
  1493.  * If one lock, put it into *TARGET.
  1494.  * Return 0 for no locks, 1 for one, 2 for two or more.
  1495.  */
  1496. {
  1497.     register struct lock *next, **trail, **found;
  1498.  
  1499.     found = 0;
  1500.     for (trail = &Locks;  (next = *trail);  trail = &next->nextlock)
  1501.         if (strcmp(getcaller(), next->login)  ==  0) {
  1502.             if (found) {
  1503.                 error("multiple revisions locked by %s; please specify one", getcaller());
  1504.                 return 2;
  1505.             }
  1506.             found = trail;
  1507.         }
  1508.     if (!found)
  1509.         return 0;
  1510.     next = *found;
  1511.     *target = next->delta;
  1512.     if (delete) {
  1513.         next->delta->lockedby = nil;
  1514.         *found = next->nextlock;
  1515.     }
  1516.     return 1;
  1517. }
  1518.  
  1519.     int
  1520. addlock(delta, verbose)
  1521.     struct hshentry * delta;
  1522.     int verbose;
  1523. /*
  1524.  * Add a lock held by caller to DELTA and yield 1 if successful.
  1525.  * Print an error message if verbose and yield -1 if no lock is added because
  1526.  * DELTA is locked by somebody other than caller.
  1527.  * Return 0 if the caller already holds the lock.
  1528.  */
  1529. {
  1530.     register struct lock *next;
  1531.  
  1532.     next=Locks;
  1533.     for (next = Locks;  next;  next = next->nextlock)
  1534.         if (cmpnum(delta->num, next->delta->num) == 0)
  1535.             if (strcmp(getcaller(), next->login) == 0)
  1536.                 return 0;
  1537.             else {
  1538.                 if (verbose)
  1539.                   error("Revision %s is already locked by %s.",
  1540.                     delta->num, next->login
  1541.                   );
  1542.                 return -1;
  1543.             }
  1544.     next = ftalloc(struct lock);
  1545.     delta->lockedby = next->login = getcaller();
  1546.     next->delta = delta;
  1547.     next->nextlock = Locks;
  1548.     Locks = next;
  1549.     return 1;
  1550. }
  1551.  
  1552.  
  1553.     int
  1554. addsymbol(num, name, rebind)
  1555.     char const *num, *name;
  1556.     int rebind;
  1557. /*
  1558.  * Associate with revision NUM the new symbolic NAME.
  1559.  * If NAME already exists and REBIND is set, associate NAME with NUM;
  1560.  * otherwise, print an error message and return false;
  1561.  * Return -1 if unsuccessful, 0 if no change, 1 if change.
  1562.  */
  1563. {
  1564.     register struct assoc *next;
  1565.  
  1566.     for (next = Symbols;  next;  next = next->nextassoc)
  1567.         if (strcmp(name, next->symbol)  ==  0)
  1568.             if (strcmp(next->num,num) == 0)
  1569.                 return 0;
  1570.             else if (rebind) {
  1571.                 next->num = num;
  1572.                 return 1;
  1573.             } else {
  1574.                 error("symbolic name %s already bound to %s",
  1575.                     name, next->num
  1576.                 );
  1577.                 return -1;
  1578.             }
  1579.     next = ftalloc(struct assoc);
  1580.     next->symbol = name;
  1581.     next->num = num;
  1582.     next->nextassoc = Symbols;
  1583.     Symbols = next;
  1584.     return 1;
  1585. }
  1586.  
  1587.  
  1588.  
  1589.     char const *
  1590. getcaller()
  1591. /* Get the caller's login name.  */
  1592. {
  1593. #    if has_setuid
  1594.         return getusername(euid()!=ruid());
  1595. #    else
  1596.         return getusername(false);
  1597. #    endif
  1598. }
  1599.  
  1600.  
  1601.     int
  1602. checkaccesslist()
  1603. /*
  1604.  * Return true if caller is the superuser, the owner of the
  1605.  * file, the access list is empty, or caller is on the access list.
  1606.  * Otherwise, print an error message and return false.
  1607.  */
  1608. {
  1609.     register struct access const *next;
  1610.  
  1611.     if (!AccessList || myself(RCSstat.st_uid) || strcmp(getcaller(),"root")==0)
  1612.         return true;
  1613.  
  1614.     next = AccessList;
  1615.     do {
  1616.         if (strcmp(getcaller(), next->login)  ==  0)
  1617.             return true;
  1618.     } while ((next = next->nextaccess));
  1619.  
  1620.     error("user %s not on the access list", getcaller());
  1621.     return false;
  1622. }
  1623.  
  1624.  
  1625.     int
  1626. dorewrite(lockflag, changed)
  1627.     int lockflag, changed;
  1628. /*
  1629.  * Do nothing if LOCKFLAG is zero.
  1630.  * Prepare to rewrite an RCS file if CHANGED is positive.
  1631.  * Stop rewriting if CHANGED is zero, because there won't be any changes.
  1632.  * Fail if CHANGED is negative.
  1633.  * Return 0 on success, -1 on failure.
  1634.  */
  1635. {
  1636.     int r = 0, e;
  1637.  
  1638.     if (lockflag)
  1639.         if (changed) {
  1640.             if (changed < 0)
  1641.                 return -1;
  1642.             putadmin();
  1643.             puttree(Head, frewrite);
  1644.             aprintf(frewrite, "\n\n%s%c", Kdesc, nextc);
  1645.             foutptr = frewrite;
  1646.         } else {
  1647. #            if bad_creat0
  1648.                 int nr = !!frewrite, ne = 0;
  1649. #            endif
  1650.             ORCSclose();
  1651.             seteid();
  1652.             ignoreints();
  1653. #            if bad_creat0
  1654.                 if (nr) {
  1655.                     nr = un_link(newRCSname);
  1656.                     ne = errno;
  1657.                     keepdirtemp(newRCSname);
  1658.                 }
  1659. #            endif
  1660.             r = un_link(lockname);
  1661.             e = errno;
  1662.             keepdirtemp(lockname);
  1663.             restoreints();
  1664.             setrid();
  1665.             if (r != 0)
  1666.                 enerror(e, lockname);
  1667. #            if bad_creat0
  1668.                 if (nr != 0) {
  1669.                     enerror(ne, newRCSname);
  1670.                     r = -1;
  1671.                 }
  1672. #            endif
  1673.         }
  1674.     return r;
  1675. }
  1676.  
  1677.     int
  1678. donerewrite(changed, keepRCStime)
  1679.     int changed, keepRCStime;
  1680. /*
  1681.  * Finish rewriting an RCS file if CHANGED is nonzero.
  1682.  * Set its mode if CHANGED is positive.
  1683.  * Keep its original modification time if keepRCStime is set.
  1684.  * Return 0 on success, -1 on failure.
  1685.  */
  1686. {
  1687.     int r = 0, e = 0;
  1688. #    if bad_creat0
  1689.         int lr, le;
  1690. #    endif
  1691.  
  1692.     if (changed && !nerror) {
  1693.         if (finptr) {
  1694.             fastcopy(finptr, frewrite);
  1695.             Izclose(&finptr);
  1696.         }
  1697.         if (1 < RCSstat.st_nlink)
  1698.             warn("breaking hard link to %s", RCSname);
  1699.         seteid();
  1700.         ignoreints();
  1701.         r = chnamemod(
  1702.             &frewrite, newRCSname, RCSname, changed,
  1703.             RCSstat.st_mode & ~(S_IWUSR|S_IWGRP|S_IWOTH),
  1704.             keepRCStime ? RCSstat.st_mtime : (time_t)-1
  1705.         );
  1706.         e = errno;
  1707.         keepdirtemp(newRCSname);
  1708. #        if bad_creat0
  1709.             lr = un_link(lockname);
  1710.             le = errno;
  1711.             keepdirtemp(lockname);
  1712. #        endif
  1713.         restoreints();
  1714.         setrid();
  1715.         if (r != 0) {
  1716.             enerror(e, RCSname);
  1717.             error("saved in %s", newRCSname);
  1718.         }
  1719. #        if bad_creat0
  1720.             if (lr != 0) {
  1721.                 enerror(le, lockname);
  1722.                 r = -1;
  1723.             }
  1724. #        endif
  1725.     }
  1726.     return r;
  1727. }
  1728.  
  1729.     void
  1730. aflush(f)
  1731.     FILE *f;
  1732. {
  1733.     if (fflush(f) != 0)
  1734.         Oerror();
  1735. }
  1736.  
  1737.     void
  1738. ORCSclose()
  1739. {
  1740.     if (0 <= fdlock) {
  1741.         if (close(fdlock) != 0)
  1742.             efaterror(lockname);
  1743.         fdlock = -1;
  1744.     }
  1745.     Ozclose(&frewrite);
  1746. }
  1747.